import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import ELEMENT from "element-ui";
import { socket, setConfig, setServiceConfig, serviceConfigEmitter } from "./init";
import CodeMirror from "vue-codemirror";

Vue.config.productionTip = false;
Vue.use(ELEMENT);
Vue.use(CodeMirror);

const app = new Vue({
    router,
    render: h => h(App)
}).$mount("#app");

app.$router.push("/serviceList");
socket.on("showMessage", (data) => {
    app.$notify({
        title: data.title,
        message: data.content,
        type: data.leval || "info",
        position: "bottom-right",
    });
});

socket.on("updateConfig", () => {
    socket.wsCallback({ type: "getConfig" }, (config) => {
        setConfig(JSON.stringify(config, null, 4), false);
    });
});

socket.on("updateServiceConfig", ({ serviceName }) => {
    socket.wsCallback({ type: "getServiceConfig", serviceName }, (serviceConfig) => {
        serviceConfigEmitter.emit("update", serviceName, serviceConfig);
        setServiceConfig(serviceName, serviceConfig, false);
    });
});

socket.on("kick", () => {
    app.$notify({
        duration: 0,
        title: "提示",
        type: "warning",
        position: "bottom-right",
        message: "该账号在其它地方登陆，当前页面已退出！",
    });
    app.$router.push("/serviceList");
    socket.id = "";
});

socket.on("logout", () => {
    socket.id = "";
});

router.beforeEach((to, from, next) => {
    if (to.meta.auth && !socket.id) {
        next({
            path: "/login",
            query: { redirect: to.fullPath },
        });
    } else {
        next();
    }
});